package lib.base

import android.annotation.SuppressLint
import android.content.pm.ActivityInfo
import android.os.Bundle
import android.view.*
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import lib.base.note.PageStatusNote
import timber.log.Timber
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type

/**
 *  author: luoXiong
 *  e-mail: 382060748@qq.com
 *  date: 2020/6/4 21:24
 *  version: 1.0
 *  desc: // QMUIActivity QMUIFragmentActivity AppCompatActivity , PageStatus
 */
abstract class BaseAct<B : ViewDataBinding, VM : BaseViewModel, M : IManager<VM>> :
    AppCompatActivity() {
    abstract val layoutId: Int
    abstract fun doBusiness(savedInstanceState: Bundle?)
    private var mBinding: B? = null
    protected lateinit var mModel: VM
    protected lateinit var mManager: M
    protected var isViewCreated = false

    // private var mLoadingDialog: MviLoadingView? = null
    private var mModelNull: VM? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //保持屏幕不暗和竖屏
        setRequestedOrientation()
        // 注入皮肤
        //skinManager = QMUISkinManager.defaultInstance(this)
        // mBinding = DataBindingUtil.inflate(LayoutInflater.from(this), layoutId, null, false)
        mBinding = DataBindingUtil.setContentView(this, layoutId)
        mBinding!!.lifecycleOwner = this
        val argsType = getActualTypeArguments()
        initViewModel(argsType)
        initManager(argsType)
        initSetVariable()
        isViewCreated = true
        setToolbarClick()
        registerUIChangeLiveDataCallBack()
        initView()
        doBusiness(savedInstanceState)
    }

    fun getB(): B {
        return mBinding!!
    }

    fun getM(): M {
        return mManager
    }

    fun getVm(): VM {
        return mModel
    }


    /**
     * 设置一直竖屏
     */
    @SuppressLint("SourceLockedOrientationActivity")
    open fun setRequestedOrientation() {
        // 一直竖屏
        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
        // 保持屏幕不暗
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
    }

    //    private val mModel2 by viewModels<VM>()
    @Suppress("UNCHECKED_CAST")
    protected fun initViewModel(argsType: Array<out Type>) {
        var model = createViewModel()
        val modelClass: Class<VM>
        if (model == null) {
            modelClass = argsType[1] as Class<VM>
            model = ViewModelProvider(this).get(modelClass)
        }
        mModel = model
        mModelNull = model
    }

    private fun initSetVariable() {
        mBinding!!.setVariable(BR.vm, mModel)
        mBinding!!.setVariable(BR.click, this)

    }

    private fun initManager(argsType: Array<out Type>) {
        val type = argsType[2]
        val defName=DefaultManager.javaClass.name
        val typeName=(type as Class<M>).name
        if (defName == typeName) {
            mManager = DefaultManager as M
        } else {
            mManager = type.newInstance()
                .setActivity(this).setViewModel(mModel) as M
        }
    }

    private fun getActualTypeArguments(): Array<out Type> {
        val type = javaClass.genericSuperclass!! as ParameterizedType
        return type.actualTypeArguments
    }

    protected open fun initView() {}


    fun setToolbarClick() {
        val childAt = (mBinding!!.root as ViewGroup).getChildAt(0)
//        if (childAt is QMUITopBarLayout) {
//            childAt.addLeftBackImageButton().setOnClickListener { clickToolbarBack() }
//        }
    }


    // 注册dialog 显示和 隐藏的事件
    open fun registerUIChangeLiveDataCallBack() {
        mModel.getUC().showDialog.observe(this, Observer<String?> {
            showLoadingDialog(it)
        })
//        mModel.getUC().dismissDialog.observe(this, Observer<Void> {
//            dismissLoadingDialog()
//        })
        mModel.getUC().pageStatusEvent.observe(this, Observer<Int> { pageStatus ->
            onReceivePageStatusEvent(pageStatus)
        })
    }

    private fun showLoadingDialog(tipWord: String? = null) {
//        if (mLoadingDialog == null) {
//            mLoadingDialog = QMUITipDialog.Builder(requireContext())
//                .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
//                .setTipWord(tipWord ?: "正在加载")
//                .create()
//            val b = XPopup.Builder(this).popupType(PopupType.Center)
//                .dismissOnTouchOutside(false)
//                .dismissOnBackPressed(MviConfig.mvi_is_debug)
//                .asCustom(MviLoadingView(this))
//            mLoadingDialog = b as MviLoadingView
//       }
//        mLoadingDialog?.setTitle(tipWord ?: "正在加载")
//        mLoadingDialog?.show()
    }


    // 接收到页面状态改变
    private fun onReceivePageStatusEvent(@PageStatusNote pageStatus: Int) {
        // Timber.d("onReceivePageStatusEvent()..接收页面状态...pageStatus=$pageStatus")
        when (pageStatus) {
            PageStatusNote.dismiss_loading_dialog -> {
                dismissLoadingDialog()
            }
            PageStatusNote.show_page_loading -> {
                //  showLoading()
            }
            PageStatusNote.show_page_empty -> {
                //  showEmpty()
            }
            PageStatusNote.show_page_error -> {
                // showError()
            }
            PageStatusNote.hide_status_layout -> {
                //  hideStatusLayout()
            }
            else -> {

            }
        }
    }

    private fun dismissLoadingDialog() {
        // Timber.d("关闭对话了..11..cc=${mLoadingDialog != null && mLoadingDialog!!.isShow}")
//        if (mLoadingDialog != null) {
//            mLoadingDialog!!.dismiss()
//        }
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == android.R.id.home) {
            clickToolbarBack()
            return true
        }
        return super.onOptionsItemSelected(item)
    }

    /**
     * 点击toolBar的返回
     */
    open protected fun clickToolbarBack() {
        onBackPressed()
    }

    /**
     * 初始化ViewModel
     *
     * @return 继承 BaseViewModel 的ViewModel
     */
    open fun createViewModel(): VM? {
        return mModelNull
    }


    override fun onDestroy() {
        super.onDestroy()
        mBinding?.unbind()
        mBinding = null
        mManager.onDestroy()
    }
}
